#include "GGXMaterial.h"

using namespace OBR;

std::shared_ptr<CudaProgram> GGXMaterial::program;
CudaBuffer GGXMaterial::sbt_data_payload;

GGXMaterial::GGXMaterial()
    : Material("shaders/Material/GGXMaterial.cu"), albedo(Spectrum(1.0f)), alpha(0.0f), eta(1.5f)
{
    this->program_desc.callables.entryFunctionNameDC = "__direct_callable__ggx_material";
    this->program_desc.kind = OPTIX_PROGRAM_GROUP_KIND_CALLABLES;
    this->program_desc.flags = OPTIX_PROGRAM_GROUP_FLAGS_NONE;
}

GGXMaterial::~GGXMaterial()
{
}

void GGXMaterial::uploadVirtualProgramPayload(
    std::vector<std::shared_ptr<VirtualProgramEntry>> instances)
{
    // collect data
    GGXMaterialData *data = new GGXMaterialData[instances.size()];
    for (size_t i = 0; i < instances.size(); i++)
    {
        auto mat = std::dynamic_pointer_cast<GGXMaterial>(instances[i]);
        data[i].albedo = mat->albedo.getDeviceMipmap();
        data[i].alpha = mat->alpha.getDeviceMipmap();
        data[i].eta = mat->eta;
    }

    // set payload
    size_t payload_size = sizeof(GGXMaterialData) * instances.size();
    this->sbt_data_payload.resize(payload_size);
    this->sbt_data_payload.upload(data, payload_size);

    delete[] data;
}

void GGXMaterial::_buildFromConfig(const Json::Value &config)
{
    if (config["type"].asString().compare("ggx") != 0)
    {
        std::cerr << "wrong config value is sent to GGXMaterial::_buildFromConfig" << std::endl;
        std::cerr << "got:" << config << std::endl;
        throw std::runtime_error("invalid parameter");
    }
    // albedo
    ColorTexture2D albedo_tex;
    ConfigHelpers::loadTexture2D<Spectrum>(config["albedo"], albedo_tex);
    this->albedo.createFromTexture(albedo_tex);
    // alpha
    FloatTexture2D alpha_tex;
    ConfigHelpers::loadTexture2D<float>(config["alpha"], alpha_tex);
    this->alpha.createFromTexture(alpha_tex);
    // eta
    this->eta = config["eta"].asFloat();
    // TODO: add roughness support
}

CUdeviceptr GGXMaterial::getPayloadDevicePtr()
{
    return GGXMaterial::sbt_data_payload.d_pointer();
}

void GGXMaterial::setProgram(std::shared_ptr<CudaProgram> prog)
{
    GGXMaterial::program = prog;
}

std::shared_ptr<CudaProgram> GGXMaterial::getProgram()
{
    return GGXMaterial::program;
}

OptixProgramGroupOptions &GGXMaterial::getProgramGroupOptions()
{
    return this->program_opt;
}

OptixProgramGroupDesc &GGXMaterial::getProgramGroupDesc()
{
    this->program_desc.callables.moduleDC = this->cuda_module->optix_module;
    return this->program_desc;
}